package gui;

import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ScrollPaneConstants;

import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;

import fn.Function;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

public class PanelFunction extends JScrollPane {

	private static final long serialVersionUID = 3784782984939801286L;

	public JPanel panel;
	private BufferedImage img = null;

	public PanelFunction() {
		init();
	}

	private void init() {
		setPreferredSize(new Dimension(128, 64));
		setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

		panel = new JPanel() {
			private static final long serialVersionUID = -9104428159339091054L;

			@Override
			public void paint(Graphics g) {
				g.setColor(Color.WHITE);
				g.fillRect(0, 0, getWidth(), getHeight());
				if (img != null)
					g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), null);
			}
		};
		panel.setPreferredSize(new Dimension(256, 64));
		panel.repaint();
		setViewportView(panel);
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGap(0, 448, Short.MAX_VALUE));
		gl_panel.setVerticalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGap(0, 298, Short.MAX_VALUE));
		panel.setLayout(gl_panel);
	}

	public void setFn(Function fn) {
		TeXIcon ti = new TeXFormula(fn.toLatex()).createTeXIcon(TeXConstants.STYLE_DISPLAY, 16);
		ti.isColored = true;
		ti.setForeground(Color.BLACK);
		panel.setSize(ti.getIconWidth(), ti.getIconHeight());
		panel.setPreferredSize(new Dimension(ti.getIconWidth(), ti.getIconHeight()));
		img = new BufferedImage(ti.getIconWidth(), ti.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
		ti.paintIcon(this, img.getGraphics(), 0, 0);
		setViewportView(panel);
		revalidate();
		repaint();
	}

}
